<?php

/**
 * WxappModel 模型
 * Class WxappModel
 */
class WxappModel
{

    public $tableName = "";
    public $errMsg = '';

    static private $_singleton;

    static public function getSingleton()
    {
        if (!self::$_singleton) {
            self::$_singleton = new static();
        }

        return self::$_singleton;
    }

    //获取access_token
    public function get_access_token(){
        $accessTokenModel = AccessTokenModel::getSingleton();
        $access_token = $accessTokenModel->find(['expires_time#>'=> time()]);
        if(!$access_token){
            $curlModel = new CurlModel();
            $wxappConfig = SmsConfigModel::getSingleton()->find(['name'=> 'wxapp']);
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential';
            $res = $curlModel->Get($url, ['appid'=> $wxappConfig['username'], 'secret'=> $wxappConfig['password']]);
            if($res){
                $access_token_arr = json_decode($res, true);
                $accessTokenModel->add([
                    'app_id'    => $wxappConfig['username'],
                    'access_token'  => $access_token_arr['access_token'],
                    'expires_time'  => time()+$access_token_arr['expires_in']
                ]);
                return $access_token_arr['access_token'];
            }

            return false;
        }
    }

    //获取二维码接口
    public function qrcode($user_id){
        $access_token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $access_token;

        $data = [
            'expire_seconds'    => 2592000,
            'action_name'       => 'QR_SCENE',
            'action_info'       => [
                'scene' => ['scene_id'=> $user_id]
            ],
        ];

        $res = $this->postDataCurl($url, $data);
    }
}